// Address parsing utilities

use std::net::{IpAddr, SocketAddr};

pub fn parse_address(addr: &str) -> Result<SocketAddr, std::io::Error> {
    // Try parsing as SocketAddr first
    if let Ok(socket_addr) = addr.parse::<SocketAddr>() {
        return Ok(socket_addr);
    }

    // Try parsing as host:port
    if let Some((host, port)) = addr.rsplit_once(':') {
        if let Ok(port) = port.parse::<u16>() {
            // Try parsing host as IP
            if let Ok(ip) = host.parse::<IpAddr>() {
                return Ok(SocketAddr::new(ip, port));
            }
            
            // If not IP, it's a domain name - resolve it
            // For now, return an error as DNS resolution requires async
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "Domain name resolution not supported in sync context",
            ));
        }
    }

    Err(std::io::Error::new(
        std::io::ErrorKind::InvalidInput,
        "Invalid address format",
    ))
}

pub fn is_valid_address(addr: &str) -> bool {
    parse_address(addr).is_ok() || addr.contains(':')
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_ipv4() {
        let addr = parse_address("127.0.0.1:8080").unwrap();
        assert_eq!(addr.port(), 8080);
    }

    #[test]
    fn test_parse_ipv6() {
        let addr = parse_address("[::1]:8080").unwrap();
        assert_eq!(addr.port(), 8080);
    }

    #[test]
    fn test_is_valid_address() {
        assert!(is_valid_address("127.0.0.1:8080"));
        assert!(is_valid_address("example.com:443"));
        assert!(!is_valid_address("invalid"));
    }
}
